package com.ikingtech.datav.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ikingtech.datav.api.FilterApi;
import com.ikingtech.datav.model.entity.FilterDO;
import com.ikingtech.datav.model.request.FilterDTO;
import com.ikingtech.datav.model.request.FilterSearchDTO;
import com.ikingtech.datav.model.result.FilterVO;
import com.ikingtech.datav.service.FilterService;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author fucb
 */
@RequiredArgsConstructor
@ApiController(value = "/filter", name = "可视化大屏-过滤器", description = "可视化大屏-过滤器")
public class FilterController implements FilterApi {

    private final FilterService filterService;

    @Override
    public R<List<FilterVO>> selectByPage(@RequestBody FilterSearchDTO param) {
        return R.ok(this.filterService.selectByPage(param).convert(entity -> BeanUtil.copyProperties(entity, FilterVO.class)));
    }

    @Override
    public R<FilterVO> getInfo(@RequestParam("id") Integer id) {
        return R.ok(this.filterService.getInfo(id));
    }

    @Override
    public R<String> add(@RequestBody FilterDTO param) {
        this.filterService.add(param);
        return R.ok();
    }

    @Override
    public R<String> edit(@RequestBody FilterDTO param) {
        this.filterService.edit(param);
        return R.ok();
    }

    @Override
    public R<String> delete(@RequestParam String id) {
        this.filterService.delete(id);
        return R.ok();
    }

    @Override
    public R<List<FilterVO>> filterLists(@RequestBody FilterSearchDTO param) {
        LambdaQueryWrapper<FilterDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .and(Tools.Str.isNotBlank(param.getProjectId()),
                        q -> q.eq(FilterDO::getProjectId, param.getProjectId())
                                .or()
                                .isNull(FilterDO::getProjectId)
                );
        queryWrapper.and(q -> q.eq(FilterDO::getScreenId, param.getScreenId()).or().isNull(FilterDO::getScreenId));
        List<FilterDO> list = this.filterService.list(queryWrapper);
        return R.ok(BeanUtil.copyToList(list, FilterVO.class));
    }

}

